package com.whh.tq.service;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.whh.tq.bean.Favorite;
import com.whh.tq.common.AbstractDBHelper;
import com.whh.tq.common.AndroidHelper;

public class FavoriteServiceImpl extends AbstractDBHelper implements
		FavoriteService {

	private Context context;
	
	public FavoriteServiceImpl(Context context){
		this.context = context;
	}
	
	@Override
	public boolean save(Favorite favorite) {
		super.open(context);
		ContentValues values = new ContentValues();
		values.put("trainCode", favorite.getTrainCode());
		values.put("station", favorite.getStation());
		values.put("desc", favorite.getDesc());
		Long uid = db.insert(getTableName(), "id", values);
		Log.i(AndroidHelper.LOG_TAG, "save favorite:"+uid);
		super.close();
		return uid>0;
	}

	@Override
	public boolean delete(int favoriteId) {
		super.open(context);
		int uid = db.delete(getTableName(), "id=" + favoriteId, null);
		Log.i(AndroidHelper.LOG_TAG,"del favorite:"+uid);
		super.close();
		return uid>0;
	}

	@Override
	public List<Favorite> getAll() {
		super.open(context);
		List<Favorite> list = new ArrayList<Favorite>();
		Cursor cursor = db.query(getTableName(), null, null, null,null, null, "id DESC");
		cursor.moveToFirst();
		while (!cursor.isAfterLast() && (cursor.getString(0) != null)) {
			Favorite fav = new Favorite();
			fav.setId(cursor.getInt(0));
			fav.setTrainCode(cursor.getString(1));
			fav.setStation(cursor.getString(2));
			fav.setDesc(cursor.getString(3));
			list.add(fav);
			cursor.moveToNext();
		}
		cursor.close();
		super.close();
		Log.i(AndroidHelper.LOG_TAG,"getAll Favorite:"+list.size());
		return list;
	}

	@Override
	public String getTableName() {
		return AndroidHelper.TABLE_FAVORITE;
	}

	@Override
	public String getCreateTableSQL() {
		return "CREATE TABLE IF NOT EXISTS "
				+ AndroidHelper.TABLE_FAVORITE
				+ "(id integer primary key, trainCode varchar, station varchar, desc varchar)";
	}

	@Override
	public boolean isExits(String trainCode, String station) {
		super.open(context);
		String selection = "";
		if(trainCode!=null){
			selection = "trainCode='"+trainCode+"'";
		}
		if(station!=null){
			selection = "station='"+station+"'";
		}
		Cursor cursor = db.query(getTableName(), null, selection, null,null, null, "id DESC");
		boolean b = cursor.moveToFirst();
		cursor.close();
		super.close();
		return b;
	}

}
